import React, { useEffect, useState } from "react";
import {
  DeleteDepartmentService,
  GetDepartmentService,
  GetMenuService,
  PatchDepartmentService,
  PostDepartmentService,
} from "@/service";
import {
  Button,
  Card,
  Form,
  Input,
  message,
  Modal,
  Popconfirm,
  Table,
  Tree,
} from "antd";
import SelectMember from "@/components/selectMember/select-member";
import { useDispatch, useSelector } from "react-redux";
import {
  IDispatch,
  IStore,
  fetchDepartmentThunk,
  fetchGetUserListThunk,
} from "@/store";

export default function () {
  const userStore = useSelector((state: IStore) => state.user);
  const dispatch = useDispatch<IDispatch>();
  // Modal 里 树结构显示的数据
  const [treeData, setTreeData] = useState<any[]>([]);
  // Modal选中的树结构
  const [checkedKeys, setCheckedKeys] = useState<any[]>([]);
  const [checkedHelfKeys, setCheckedHelfKeys] = useState<any[]>([]);
  function GetDepartment() {
    GetMenuService().then((res) => {
      const data = res.data.list.map((item: any) => ({
        title: item.name,
        key: item.ID,
        children:
          item.children?.map((itemy: any) => ({
            title: itemy.name,
            key: itemy.ID,
          })) ?? [],
      }));
      setTreeData(data);
    });
  }
  useEffect(() => {
    dispatch(fetchDepartmentThunk());
    GetDepartment();
  }, []);

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [operateTitle, setOperateTitle] = useState("");
  const [modalData, setModalData] = useState<any>({});

  const showModal = async (data?: any) => {
    setIsModalOpen(true);
    if (!data) {
      setOperateTitle("添加");
    } else {
      setOperateTitle("编辑");
      setModalData(data);
      const menu = await GetMenuService(data.permissions);
      let checkedKey: any[] = [];
      menu.data.list.forEach((item: any) => {
        item.children?.forEach((itemy: any) => {
          checkedKey.push(itemy.ID);
        });
      });
      const half = menu.data.list.map((item: any) => item.ID);
      setCheckedKeys(checkedKey);
      setCheckedHelfKeys(half);
    }
  };

  const handleOk = async () => {
    if (!modalData.name) {
      message.warning("部门名称不能为空！！！");
      return;
    }
    if (operateTitle == "添加") {
      const res: any = await PostDepartmentService({
        ...modalData,
        name: modalData.name,
        permissions: [...new Set([...checkedHelfKeys, ...checkedKeys])].join(
          ","
        ),
      });
      if (!res.code) {
        message.success(res.msg);
      } else {
        message.warning(res.msg);
        return;
      }
    } else {
      await PatchDepartmentService({
        ...modalData,
        name: modalData.name,
        permissions: [...new Set([...checkedHelfKeys, ...checkedKeys])].join(
          ","
        ),
      });
    }

    setIsModalOpen(false);
    GetDepartment();
    dispatch(fetchDepartmentThunk());
  };

  const handleCancel = () => {
    setIsModalOpen(false);
    setModalData({});
    setCheckedKeys([]);
    setCheckedHelfKeys([]);
  };
  const columns = [
    {
      title: "部门名称",
      dataIndex: "name",
      width: "120px",
    },

    {
      title: "审核人员",
      render: (_, r) => {
        const MustSign = [
          ...r.MustSign?.split(","),
          ...r.OrSign?.split(","),
        ].reduce((pre, curr) => {
          if (pre == "") {
            return curr;
          } else {
            return pre + "," + curr;
          }
        }, "");
        return (
          <SelectMember
            flag={false}
            setAttrKey={() => {}}
            attrData={{ MustSign }}
            data={userStore.users}
            attrKey="MustSign"
          ></SelectMember>
        );
      },
    },
    {
      title: "抄送人员",
      render: (_, r) => {
        return (
          <SelectMember
            flag={false}
            setAttrKey={() => {}}
            attrData={{ Notify: r.Notify }}
            data={userStore.users}
            attrKey="Notify"
          ></SelectMember>
        );
      },
    },
    {
      title: "操作",
      fixed: "right",
      width: "180px",
      render: (text: string, record: any, index: number) => (
        <div className="gap-3 flex">
          <Button onClick={() => showModal(record)} type="primary">
            编辑
          </Button>
          <Popconfirm
            title="部门操作"
            description="是否删除该部门?"
            onConfirm={async () => {
              await DeleteDepartmentService(record);
              await dispatch(fetchDepartmentThunk());
              await dispatch(fetchGetUserListThunk());
              GetDepartment();
            }}
            okText="Yes"
            cancelText="No"
          >
            <Button type="primary" danger>
              删除
            </Button>
          </Popconfirm>
        </div>
      ),
    } as const,
  ];
  return (
    <Card className=" overflow-auto">
      <Button className="w-full" type="primary" onClick={() => showModal()}>
        添加
      </Button>
      <Table
        scroll={{
          x: 1200,
        }}
        dataSource={userStore.department.map((item) => ({
          key: item.ID,
          ...item,
        }))}
        columns={columns}
      />
      <Modal
        destroyOnClose
        title={operateTitle}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <div className="max-w-[550px] h-[550px] overflow-y-auto">
          <div className="flex items-center">
            <span className="w-24">部门名称: </span>
            <Input
              value={modalData.name}
              onChange={(event) => {
                setModalData({
                  ...modalData,
                  name: event.target.value,
                });
              }}
            ></Input>
          </div>
          <span>菜单权限: </span>
          <Tree
            checkedKeys={{
              checked: checkedKeys,
              halfChecked: checkedHelfKeys,
            }}
            checkable
            onCheck={(checkedKeys, e) => {
              setCheckedKeys(checkedKeys as any[]);
              setCheckedHelfKeys(e.halfCheckedKeys as any[]);
            }}
            treeData={treeData}
          />
          <span>审核人员（必须）</span>
          <SelectMember
            flag={true}
            setAttrKey={setModalData}
            attrData={modalData}
            data={userStore.users}
            attrKey="MustSign"
          ></SelectMember>
          <span>审核人员（或审核）</span>
          <SelectMember
            flag={true}
            setAttrKey={setModalData}
            attrData={modalData}
            data={userStore.users}
            attrKey="OrSign"
          ></SelectMember>
          <span>抄送人</span>
          <SelectMember
            flag={true}
            setAttrKey={setModalData}
            attrData={modalData}
            data={userStore.users}
            attrKey="Notify"
          ></SelectMember>
        </div>
      </Modal>
    </Card>
  );
}
